

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/fluid.png">
  <link rel="icon" href="/blog/images/base.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Airfe">
  <meta name="keywords" content="">
  
    <meta name="description" content="本文将概括JavaScript中变量可以包含的两种不同类型数据：原始值和引用值。">
<meta property="og:type" content="article">
<meta property="og:title" content="原始值和引用值概括">
<meta property="og:url" content="https://airfe.gitee.io/blog/2023/04/13/%E5%8E%9F%E5%A7%8B%E5%80%BC%E5%92%8C%E5%BC%95%E7%94%A8%E5%80%BC%E6%A6%82%E6%8B%AC/index.html">
<meta property="og:site_name" content="Airfe的博客">
<meta property="og:description" content="本文将概括JavaScript中变量可以包含的两种不同类型数据：原始值和引用值。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/pageImage/JavaScript%E5%87%BD%E6%95%B0.png">
<meta property="article:published_time" content="2023-04-13T00:00:00.000Z">
<meta property="article:modified_time" content="2024-02-26T12:25:20.449Z">
<meta property="article:author" content="Airfe">
<meta property="article:tag" content="js">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/pageImage/JavaScript%E5%87%BD%E6%95%B0.png">
  
  
  
    <meta name="referrer" content="no-referrer" />
  
  <title>原始值和引用值概括 - Airfe的博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"airfe.gitee.io","root":"/blog/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":"699a5d71ac7179b23874a59b0666a6f6","google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","app_key":"P5fzMTGSJIoTaGvmgzsUHeNZ","server_url":"https://rw68dmke.lc-cn-n1-shared.com","path":"window.location.pathname","ignore_local":false}},"search_path":"/blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/blog/js/utils.js" ></script>
  <script  src="/blog/js/color-schema.js" ></script>
  

  
    <!-- Baidu Analytics -->
    <script async>
      if (!Fluid.ctx.dnt) {
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?699a5d71ac7179b23874a59b0666a6f6";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
      }
    </script>
  

  

  

  

  

  

  
    
  



  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/blog/">
      <strong>Airfe</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/links/">
                <i class="iconfont icon-link-fill"></i>
                <span>友链</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/blog/images/bg.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="原始值和引用值概括"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-04-13 08:00" pubdate>
          2023年04月13日
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          7.2k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          61 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">原始值和引用值概括</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="变量值"><a href="#变量值" class="headerlink" title="变量值"></a>变量值</h1><p>ECMAScript变量可以包含两种不同类型的数据：<strong>原始值和引用值</strong>。</p>
<p>原始值（primitive value）就是最简单的数据，引用值（reference value）则是由多个值构成的对象。</p>
<p>在把一个值赋给变量时，JavaScript 引擎必须确定这个值是原始值还是引用值。</p>
<p><strong>保存原始值的变量是按值（by value）访问的</strong>，因为我们操作的就是存储在变量中的<strong>实际值</strong>；</p>
<p>引用值是保存在内存中的对象，<strong>保存引用值的变量是按引用（by reference）访问的</strong>。在操作对象时，实际上操作的是对该对象的<strong>引用</strong>（reference）而非实际的对象本身。</p>
<blockquote>
<p>6种简单数据类型的值都是原始值。</p>
</blockquote>
<h2 id="动态属性"><a href="#动态属性" class="headerlink" title="动态属性"></a>动态属性</h2><p>原始值不能有属性，而对于引用值而言，可以随时添加、修改和删除其属性和方法。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> person = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Object</span>(); <br>person.<span class="hljs-property">name</span> = <span class="hljs-string">&quot;Nicholas&quot;</span>; <br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(person.<span class="hljs-property">name</span>); <span class="hljs-comment">// &quot;Nicholas&quot;</span><br><br><span class="hljs-keyword">let</span> name = <span class="hljs-string">&quot;Nicholas&quot;</span>; <br>name.<span class="hljs-property">age</span> = <span class="hljs-number">27</span>; <br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name.<span class="hljs-property">age</span>);    <span class="hljs-comment">// undefined</span><br></code></pre></td></tr></table></figure>

<p>但如果使用new关键字，显示的创建Number、String、Boolean原始值包装类型对象， 也可以使该变量拥引用值的行为。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> name1 = <span class="hljs-string">&quot;Nicholas&quot;</span>; <br><span class="hljs-keyword">let</span> name2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(<span class="hljs-string">&quot;Matt&quot;</span>); <br><br>name1.<span class="hljs-property">age</span> = <span class="hljs-number">27</span>; <br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name1.<span class="hljs-property">age</span>); <span class="hljs-comment">// undefined </span><br><br>name2.<span class="hljs-property">age</span> = <span class="hljs-number">26</span>; <br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name2.<span class="hljs-property">age</span>); <span class="hljs-comment">// 26 </span><br><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">typeof</span> name1); <span class="hljs-comment">// string </span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">typeof</span> name2); <span class="hljs-comment">// object</span><br></code></pre></td></tr></table></figure>

<h2 id="复制值"><a href="#复制值" class="headerlink" title="复制值"></a>复制值</h2><p>除了存储方式不同，原始值和引用值在通过变量复制时也有所不同。</p>
<ul>
<li>原始值复制</li>
</ul>
<p>在通过变量把一个原始值赋值到另一个变量时，原始值会被复制到新变量的位置。这两个变量可以独立使用，互不干扰。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> num1 = <span class="hljs-number">5</span>; <br><span class="hljs-keyword">let</span> num2 = num1;<br></code></pre></td></tr></table></figure>

<img src="" srcset="/blog/img/loading.gif" lazyload data-original="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/%20markdown/image-20230427221404929.png" alt="image-20230427221404929" style="zoom:80%;">

<ul>
<li>引用值复制</li>
</ul>
<p>在把引用值从一个变量赋给另一个变量时，存储在变量中的值也会被复制到新变量所在的位置。</p>
<p>区别在于，这里复制的值实际上是一个指针，指向存储在堆内存中的对象。操作完成后，两个变量实际上指向同一个对象。</p>
<p>因此一个对象上面的变化会在另一个对象上反映出来。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> obj1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Object</span>(); <br><span class="hljs-keyword">let</span> obj2 = obj1; <br>obj1.<span class="hljs-property">name</span> = <span class="hljs-string">&quot;Nicholas&quot;</span>; <br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj2.<span class="hljs-property">name</span>); <span class="hljs-comment">// &quot;Nicholas&quot;</span><br></code></pre></td></tr></table></figure>

<img src="" srcset="/blog/img/loading.gif" lazyload data-original="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/%20markdown/image-20230427221423536.png" alt="image-20230427221423536" style="zoom:80%;">

<h2 id="instanceof操作符"><a href="#instanceof操作符" class="headerlink" title="instanceof操作符"></a>instanceof操作符</h2><p>我们通常不关心一个引用值是不是对象，而是想知道它是什么类型的对象。<code>instanceof</code>操作符用来确定引用值类型。</p>
<p>如果变量是给定引用类型（由其原型链决定）的实例，则<code>instanceof</code>操作符返回<code>true</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(person <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">Object</span>);  <span class="hljs-comment">// 变量 person 是 Object 吗？</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(colors <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">Array</span>);   <span class="hljs-comment">// 变量 colors 是 Array 吗？</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(pattern <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">RegExp</span>); <span class="hljs-comment">// 变量 pattern 是 RegExp 吗？</span><br></code></pre></td></tr></table></figure>

<h1 id="引用类型"><a href="#引用类型" class="headerlink" title="引用类型"></a>引用类型</h1><h2 id="基本引用类型"><a href="#基本引用类型" class="headerlink" title="基本引用类型"></a>基本引用类型</h2><h3 id="Date"><a href="#Date" class="headerlink" title="Date"></a>Date</h3><p>要创建日期对象，就使用<code>new</code>操作符来调用<code>Date</code>构造函数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> now = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>();<br></code></pre></td></tr></table></figure>

<p>要基于其他日期和时间创建日期对象，必须传入其毫秒表示（UNIX 纪元 1970 年 1 月 1 日午夜之后的毫秒数）。</p>
<p><code>Date.parse()</code>方法接收一个表示日期的字符串参数，尝试将这个字符串转换为表示该日期的毫秒数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 创建一个表示“2019 年 5 月 23 日”的日期对象</span><br><span class="hljs-keyword">let</span> someDate = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">parse</span>(<span class="hljs-string">&quot;May 23, 2019&quot;</span>));<br><span class="hljs-comment">// 如果直接把表示日期的字符串传给 Date 构造函数，那么 Date 会在后台调用 Date.parse()</span><br><span class="hljs-keyword">let</span> someDate = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>(<span class="hljs-string">&quot;May 23, 2019&quot;</span>);<br></code></pre></td></tr></table></figure>

<p><code>Date.UTC()</code>方法也返回日期的毫秒表示，传给 Date.UTC()的参数是年、零起点月数（1 月是 0，2 月是 1，以此类推）、日（1-31）、时（0-23）、分、秒和毫</p>
<p>秒。有前两个（年和月）是必需的。如果不提供日，那么默认为 1 日。其他参数的默认值都是 0。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// GMT 时间 2000 年 1 月 1 日零点</span><br><span class="hljs-keyword">let</span> y2k = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">UTC</span>(<span class="hljs-number">2000</span>, <span class="hljs-number">0</span>)); <br><span class="hljs-comment">// GMT 时间 2005 年 5 月 5 日下午 5 点 55 分 55 秒</span><br><span class="hljs-keyword">let</span> allFives = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">UTC</span>(<span class="hljs-number">2005</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">17</span>, <span class="hljs-number">55</span>, <span class="hljs-number">55</span>));<br></code></pre></td></tr></table></figure>

<p>同样的，如果直接把表示日期的字符串传给 <code>Date</code> 构造函数，那么 <code>Date</code> 会在后台调用 <code>Date.parse()</code>。</p>
<p><code>Date</code> 类型有几个专门用于格式化日期的方法，它们都会返回字符串</p>
<ul>
<li>toDateString()显示日期中的周几、月、日、年（格式特定于实现）；</li>
<li>toTimeString()显示日期中的时、分、秒和时区（格式特定于实现）；</li>
<li>toLocaleDateString()显示日期中的周几、月、日、年（格式特定于实现和地区）；</li>
<li>toLocaleTimeString()显示日期中的时、分、秒（格式特定于实现和地区）；</li>
<li>toUTCString()显示完整的UTC 日期（格式特定于实现）。</li>
</ul>
<h3 id="RegExp"><a href="#RegExp" class="headerlink" title="RegExp"></a>RegExp</h3><p>ECMAScript 通过RegExp 类型支持正则表达式。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> expression = <span class="hljs-regexp">/pattern/</span>flags;<br></code></pre></td></tr></table></figure>

<p>这个正则表达式的<code>pattern</code>（模式）可以是任何简单或复杂的正则表达式，包括字符类、限定符、分组、向前查找和反向引用。</p>
<p>每个正则表达式可以带零个或多个<code>flags</code>（标记），用于控制正则表达式的行为。</p>
<p>下面给出了表示匹配模式的标记：</p>
<ul>
<li>g：全局模式，表示查找字符串的全部内容，而不是找到第一个匹配的内容就结束。</li>
<li>i：不区分大小写，表示在查找匹配时忽略pattern 和字符串的大小写。</li>
<li>m：多行模式，表示查找到一行文本末尾时会继续查找。</li>
<li>y：粘附模式，表示只查找从lastIndex 开始及之后的字符串。</li>
<li>u：Unicode 模式，启用Unicode 匹配。</li>
<li>s：dotAll 模式，表示元字符.匹配任何字符（包括\n 或\r）。</li>
</ul>
<p>使用不同模式和标记可以创建出各种正则表达式，比如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 匹配字符串中的所有&quot;at&quot;</span><br><span class="hljs-keyword">let</span> pattern1 = <span class="hljs-regexp">/at/g</span>;<br><span class="hljs-comment">// 匹配第一个&quot;bat&quot;或&quot;cat&quot;，忽略大小写</span><br><span class="hljs-keyword">let</span> pattern2 = <span class="hljs-regexp">/[bc]at/i</span>;<br><span class="hljs-comment">// 匹配所有以&quot;at&quot;结尾的三字符组合，忽略大小写</span><br><span class="hljs-keyword">let</span> pattern3 = <span class="hljs-regexp">/.at/gi</span>;<br></code></pre></td></tr></table></figure>

<p>详细见 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions">正则表达式</a></p>
<p>除了<strong>字面量形式</strong>外，正则表达式也可以使用<strong>RegExp 构造函数</strong>来创建，它接收两个参数：模式字符串和（可选的）标记字符串。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 匹配第一个&quot;bat&quot;或&quot;cat&quot;，忽略大小写</span><br><span class="hljs-keyword">let</span> pattern1 = <span class="hljs-regexp">/[bc]at/i</span>;<br><span class="hljs-comment">// 跟pattern1 一样，只不过是用构造函数创建的</span><br><span class="hljs-keyword">let</span> pattern2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">RegExp</span>(<span class="hljs-string">&quot;[bc]at&quot;</span>, <span class="hljs-string">&quot;i&quot;</span>);<br></code></pre></td></tr></table></figure>

<p>**RegExp 实例主要方法是<code>exec()</code>**，用于配合捕获组使用。这个方法只接收一个参数，即要应用模式的字符串。如果找到了匹配项，则返回包含第一个匹配信息的</p>
<p>数组；如果没找到匹配项，则返回<code>null</code>。</p>
<p>返回的数组包含两个额外的属性：index 和input。index 是字符串中匹配的起始位置，input 是要进行匹配的字符串（即exec接收的字符串）。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> text = <span class="hljs-string">&#x27;a cat go and a cat come&#x27;</span>;<br>l4 = <span class="hljs-regexp">/a\s((cat)\sgo)/g</span>;<br>l4.<span class="hljs-title function_">exec</span>(text)<br><span class="hljs-comment">// (3) [&quot;a cat go&quot;, &quot;cat go&quot;, &quot;cat&quot;, index: 0, input: &quot;a cat go and a cat come&quot;, groups: undefined]</span><br></code></pre></td></tr></table></figure>

<h3 id="原始值包装类型"><a href="#原始值包装类型" class="headerlink" title="原始值包装类型"></a>原始值包装类型</h3><p>为了方便操作原始值，<strong>ECMAScript 提供了 3 种特殊的引用类型：Boolean、Number 和 String</strong>。</p>
<p>除了可以用new显式地创建原始值包装类型的实例，还可以直接使用原始值的方法或属性，隐式地自动创建原始值包装对象。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> s1 = <span class="hljs-string">&quot;some text&quot;</span>; <br><span class="hljs-keyword">let</span> s2 = s1.<span class="hljs-title function_">substring</span>(<span class="hljs-number">2</span>);<br></code></pre></td></tr></table></figure>

<p>引用类型与原始值包装类型的主要区别在于对象的生命周期。在通过 new 实例化引用类型后，得到的实例会在离开作用域时被销毁，而自动创建的原始值包装对</p>
<p>象则只存在于访问它的那行代码执行期间。这意味着不能在运行时给原始值添加属性和方法。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> s1 = <span class="hljs-string">&quot;some text&quot;</span>; <br>s1.<span class="hljs-property">color</span> = <span class="hljs-string">&quot;red&quot;</span>; <br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(s1.<span class="hljs-property">color</span>); <span class="hljs-comment">// undefined</span><br></code></pre></td></tr></table></figure>

<p>这里的第二行代码尝试给字符串 <code>s1</code> 添加了一个 <code>color</code> 属性。可是，第三行代码访问<code>color</code>属性时，它却不见了。原因就是第二行代码运行时会临时创建一个</p>
<p><code>String</code>对象，而当第三行代码执行时，这个对象已经被销毁了。实际上，第三行代码在这里创建了自己的<code>String</code>对象，但这个对象没有<code>color</code>属性。</p>
<p>注意，使用<code>new</code>调用原始值包装类型的构造函数，与调用同名的转型函数并不一样。例如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> value = <span class="hljs-string">&quot;25&quot;</span>; <br><span class="hljs-keyword">let</span> number = <span class="hljs-title class_">Number</span>(value);  <span class="hljs-comment">// 转型函数</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">typeof</span> number);  <span class="hljs-comment">// &quot;number&quot; </span><br><span class="hljs-keyword">let</span> obj = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Number</span>(value); <span class="hljs-comment">// 构造函数</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">typeof</span> obj);     <span class="hljs-comment">// &quot;object&quot;</span><br></code></pre></td></tr></table></figure>

<h3 id="单例内置对象Global和Math"><a href="#单例内置对象Global和Math" class="headerlink" title="单例内置对象Global和Math"></a>单例内置对象Global和Math</h3><p>当代码开始执行时，全局上下文中会存在两个内置对象：<strong>Global 和 Math</strong>。其中，<code>Global</code> 对象在大多数 <code>ECMAScript</code> 实现中无法直接访问。不过，浏览器将其</p>
<p>实现为<code>window</code> 对象。所有全局变量和函数都是 <code>Global</code> 对象的属性。<code>Math</code> 对象包含辅助完成复杂计算的属性和方法。</p>
<h2 id="集合引用类型"><a href="#集合引用类型" class="headerlink" title="集合引用类型"></a>集合引用类型</h2><h3 id="Object"><a href="#Object" class="headerlink" title="Object"></a>Object</h3><p>创建方式</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> obj=&#123;&#125;;<span class="hljs-comment">//对象字面量</span><br>或<br><span class="hljs-keyword">let</span> obj <span class="hljs-keyword">new</span> <span class="hljs-title class_">Object</span>();<span class="hljs-comment">// 使用 new 操作符和 Object 构造函数</span><br></code></pre></td></tr></table></figure>

<p>访问对象属性的方法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> obj=&#123;<span class="hljs-attr">name</span>:<span class="hljs-string">&quot;lly&quot;</span>,<span class="hljs-attr">sex</span>:<span class="hljs-string">&quot;Man&quot;</span>&#125;<br>obj.<span class="hljs-property">name</span>    <span class="hljs-comment">//点语法</span><br>或<br>obj[<span class="hljs-string">&quot;name&quot;</span>] <span class="hljs-comment">//中括号</span><br></code></pre></td></tr></table></figure>

<blockquote>
<p>在使用对象字面量表示法定义对象时，不会实际调用Object构造函数。</p>
</blockquote>
<p>关于Object更全面，更深层次的学习，作者会单独开篇。</p>
<h3 id="Array"><a href="#Array" class="headerlink" title="Array"></a>Array</h3><p>跟其他语言中的数组一样，ECMAScript 数组也是一组有序的数据，但跟其他语言不同的是，数组中每个槽位可以存储任意类型的数据。</p>
<p>ECMAScript 数组也是动态大小的，会随着数据添加而自动增长。</p>
<p>关于Array更全面，更深层次的学习，作者会单独开篇。</p>
<h3 id="Map"><a href="#Map" class="headerlink" title="Map"></a>Map</h3><h4 id="基本API"><a href="#基本API" class="headerlink" title="基本API"></a>基本API</h4><table>
<thead>
<tr>
<th>API</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>new Map()</td>
<td>创建新的 Map 对象。</td>
</tr>
<tr>
<td>set()</td>
<td>为 Map 对象中的键设置值。</td>
</tr>
<tr>
<td>get()</td>
<td>获取 Map 对象中键的值。</td>
</tr>
<tr>
<td>entries()</td>
<td>取得映射实例默认的迭代器，返回 Map 对象中键&#x2F;值对的数组。</td>
</tr>
<tr>
<td>keys()</td>
<td>返回 Map 对象中键的数组。</td>
</tr>
<tr>
<td>values()</td>
<td>返回 Map 对象中值的数组。</td>
</tr>
<tr>
<td>has()</td>
<td>如果键存在，则返回 true。</td>
</tr>
<tr>
<td>delete()</td>
<td>删除由键指定的元素。</td>
</tr>
<tr>
<td>clear()</td>
<td>删除 Map 中的所有元素。</td>
</tr>
<tr>
<td>forEach()</td>
<td>为每个键&#x2F;值对调用回调。</td>
</tr>
</tbody></table>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// new Map()创建一个空映射</span><br><span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>();<br><br><span class="hljs-comment">// set()为 Map 对象中的键设置值。</span><br>m.<span class="hljs-title function_">set</span>(<span class="hljs-string">&quot;key1&quot;</span>, <span class="hljs-string">&quot;val1&quot;</span>) <br> .<span class="hljs-title function_">set</span>(<span class="hljs-string">&quot;key2&quot;</span>, <span class="hljs-string">&quot;val2&quot;</span>);<br><br><span class="hljs-comment">// 或者使用嵌套数组初始化</span><br><span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>([<br> [<span class="hljs-string">&quot;key1&quot;</span>, <span class="hljs-string">&quot;val1&quot;</span>], <br> [<span class="hljs-string">&quot;key2&quot;</span>, <span class="hljs-string">&quot;val2&quot;</span>]<br>]);<br><br><span class="hljs-comment">// get()获取 Map 对象中键的值。</span><br><span class="hljs-title function_">alert</span>(m.<span class="hljs-title function_">get</span>(<span class="hljs-string">&quot;key1&quot;</span>)); <span class="hljs-comment">// val1</span><br><br><span class="hljs-comment">// entries()取得映射实例的默认迭代器，以插入的顺序生成[key, value]形式的数组</span><br><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> pair <span class="hljs-keyword">of</span> m.<span class="hljs-title function_">entries</span>()) &#123; <br> <span class="hljs-title function_">alert</span>(pair);   <br> <span class="hljs-comment">// [key1,val1]   </span><br> <span class="hljs-comment">// [key2,val2]</span><br>&#125;<br><br><span class="hljs-comment">// keys()和 values()分别返回以插入顺序生成键和值的迭代器</span><br><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> key <span class="hljs-keyword">of</span> m.<span class="hljs-title function_">keys</span>()) &#123; <br> <span class="hljs-title function_">alert</span>(key); <br> <span class="hljs-comment">// key1</span><br> <span class="hljs-comment">// key2</span><br>&#125;<br><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> key <span class="hljs-keyword">of</span> m.<span class="hljs-title function_">values</span>()) &#123; <br> <span class="hljs-title function_">alert</span>(key); <br> <span class="hljs-comment">// val1</span><br> <span class="hljs-comment">// val2</span><br>&#125;<br><span class="hljs-comment">// forEach(callback, opt_thisArg) 依次迭代每个键/值对</span><br>m.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">val, key</span>) =&gt;</span> <span class="hljs-title function_">alert</span>(<span class="hljs-string">`<span class="hljs-subst">$&#123;key&#125;</span> -&gt; <span class="hljs-subst">$&#123;val&#125;</span>`</span>)); <br><span class="hljs-comment">// key1 -&gt; val1</span><br><span class="hljs-comment">// key2 -&gt; val2</span><br></code></pre></td></tr></table></figure>

<p>属性</p>
<table>
<thead>
<tr>
<th>Property</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td>size</td>
<td>获取并返回 Map 对象中键值对的数量</td>
</tr>
</tbody></table>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-title function_">alert</span>(m.<span class="hljs-property">size</span>); <span class="hljs-comment">// 2</span><br></code></pre></td></tr></table></figure>

<h4 id="Object-vs-Map"><a href="#Object-vs-Map" class="headerlink" title="Object vs Map"></a>Object vs Map</h4><table>
<thead>
<tr>
<th></th>
<th>Object</th>
<th>Map</th>
</tr>
</thead>
<tbody><tr>
<td>键类型</td>
<td>必须是字符串（或符号）</td>
<td><strong>可以是任何数据类型</strong></td>
</tr>
<tr>
<td>键顺序</td>
<td>对象键没有很好地排序</td>
<td>Map 键按插入排序（故可进行迭代操作）</td>
</tr>
<tr>
<td>默认</td>
<td>有</td>
<td>无</td>
</tr>
</tbody></table>
<h4 id="WeakMap-vs-Map"><a href="#WeakMap-vs-Map" class="headerlink" title="WeakMap vs Map"></a>WeakMap vs Map</h4><p><code>WeakMap</code>是 ES6 中新增的一种集合类型，叫做“弱映射”。它与<code>Map</code>的区别就在于这个<strong>弱字</strong>，API 还是<code>Map</code>的那套（只有<code>set</code> <code>get</code> <code>has</code> <code>delete</code>) 。</p>
<p>一个对象若只被弱引用所引用，则被认为是不可访问（或弱可访问）的，即垃圾回收机制不将该引用考虑在内。只要所引用的对象的其他引用都被清除，垃圾回收</p>
<p>机制就会释放该对象所占用的内存。也就是说，一旦不再需要，<code>WeakMap</code> 里面的键名对象和所对应的键值对会自动消失，不用手动删除引用。</p>
<table>
<thead>
<tr>
<th></th>
<th>WeakMap</th>
<th>Map</th>
</tr>
</thead>
<tbody><tr>
<td>键类型</td>
<td>必须是对象（但不能是null）</td>
<td><strong>可以是任何数据类型</strong></td>
</tr>
<tr>
<td>迭代</td>
<td>不能被遍历</td>
<td>可以被遍历</td>
</tr>
<tr>
<td>是否需要手动删除引用释放内存</td>
<td>不需要，垃圾回收机制自动释放</td>
<td>必须手动释放</td>
</tr>
</tbody></table>
<h3 id="Set"><a href="#Set" class="headerlink" title="Set"></a>Set</h3><p>Set 是唯一值的集合（无重复值），一个 Set 可以容纳任何数据类型的任何值。</p>
<p>Set 在很多方面都像是加强的 Map，这是因为它们的大多数 API 和行为都是共有的。区别可能在于Map是基于“键&#x2F;值”机制存储的。</p>
<h4 id="基本API-1"><a href="#基本API-1" class="headerlink" title="基本API"></a>基本API</h4><table>
<thead>
<tr>
<th>API</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>new Set()</td>
<td>创建新的 Set 对象。</td>
</tr>
<tr>
<td>add()</td>
<td>向 Set 添加新元素。</td>
</tr>
<tr>
<td>clear()</td>
<td>从 Set 中删除所有元素。</td>
</tr>
<tr>
<td>delete()</td>
<td>删除由其值指定的元素。</td>
</tr>
<tr>
<td>entries()</td>
<td>返回一个迭代器，按照插入顺序生成包含两个元素（值的重复出现）的数组。</td>
</tr>
<tr>
<td>has()</td>
<td>如果值存在则返回 true。</td>
</tr>
<tr>
<td>forEach()</td>
<td>为每个元素调用回调。</td>
</tr>
<tr>
<td>keys()</td>
<td>取得集合实例默认的迭代器，返回 Set 对象中值的数组。</td>
</tr>
<tr>
<td>values()</td>
<td>与 keys() 相同，keys()的别名。</td>
</tr>
</tbody></table>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> s = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Set</span>([<span class="hljs-string">&quot;val1&quot;</span>, <span class="hljs-string">&quot;val2&quot;</span>]); <br><br><span class="hljs-comment">// keys()取得集合实例默认的迭代器，返回 Set 对象中值的数组。</span><br><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> value <span class="hljs-keyword">of</span> s.<span class="hljs-title function_">values</span>()) &#123; <br> 	<span class="hljs-title function_">alert</span>(value); <br>    <span class="hljs-comment">// val1 </span><br>    <span class="hljs-comment">// val2 </span><br>&#125; <br><span class="hljs-comment">// entries()返回一个迭代器，按照插入顺序生成包含两个元素（值的重复出现）的数组。</span><br><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> pair <span class="hljs-keyword">of</span> s.<span class="hljs-title function_">entries</span>()) &#123; <br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(pair); <br><span class="hljs-comment">// [&quot;val1&quot;, &quot;val1&quot;] </span><br><span class="hljs-comment">// [&quot;val2&quot;, &quot;val2&quot;] </span><br>&#125; <br></code></pre></td></tr></table></figure>

<p>属性</p>
<table>
<thead>
<tr>
<th>Property</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td>size</td>
<td>获取并返回 Set对象中值的数量。</td>
</tr>
</tbody></table>
<h4 id="WeakSet-vs-Set"><a href="#WeakSet-vs-Set" class="headerlink" title="WeakSet vs Set"></a>WeakSet vs Set</h4><p>参考<code>WeakMap</code>弱映射的理解，<code>WeakSet</code>弱集合的”弱“也是针对于<code>JavaScript</code> 垃圾回收程序对待“弱集合”中值的方式。</p>
<table>
<thead>
<tr>
<th></th>
<th>WeakSet</th>
<th>Set</th>
</tr>
</thead>
<tbody><tr>
<td>值类型</td>
<td>必须是对象（但不能是null）</td>
<td><strong>可以是任何数据类型</strong></td>
</tr>
<tr>
<td>迭代</td>
<td>不能被遍历</td>
<td>可以被遍历</td>
</tr>
<tr>
<td>是否需要手动删除引用释放内存</td>
<td>不需要，垃圾回收机制自动释放</td>
<td>必须手动释放</td>
</tr>
</tbody></table>
<blockquote>
<p>在前面介绍的集合引用类型中，Array、Map、Set 这4 种原生集合类型均定义了默认迭代器。其实还包括所有的定型数组。</p>
</blockquote>
<h2 id="特殊引用类型"><a href="#特殊引用类型" class="headerlink" title="特殊引用类型"></a>特殊引用类型</h2><p><code>JavaScript</code>比较独特的一点是，函数实际上是<code>Function</code>类型的实例，也就是说函数也是对象。因为函数也是对象，所以函数也有方法，可以用于增强其能力。</p>
<p>关于<code>Function</code>更全面，更深层次的学习，作者会单独开篇。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/blog/categories/%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF%E6%A0%88/" class="category-chain-item">前端技术栈</a>
  
  
    <span>></span>
    
  <a href="/blog/categories/%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF%E6%A0%88/js/" class="category-chain-item">js</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/blog/tags/js/">#js</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>原始值和引用值概括</div>
      <div>https://airfe.gitee.io/blog/2023/04/13/原始值和引用值概括/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Airfe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年4月13日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/blog/2023/04/13/JavaScript%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80/" title="JavaScript语言基础">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">JavaScript语言基础</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/blog/2023/04/12/HTML5%E7%89%B9%E6%80%A7/" title="HTML5特性">
                        <span class="hidden-mobile">HTML5特性</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","appKey":"P5fzMTGSJIoTaGvmgzsUHeNZ","path":"window.location.pathname","placeholder":"发表你的看法吧~","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false,"appid":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","appkey":"P5fzMTGSJIoTaGvmgzsUHeNZ","server_url":"https://rw68dmke.lc-cn-n1-shared.com"},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
        <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> <div style="font-size: 0.85rem"> <span id="timeDate">载入天数</span> <span id="times">载入时分秒</span> <script src="js/duration.js"></script> </div> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="leancloud-site-pv-container" style="display: none">
        总访问量 
        <span id="leancloud-site-pv"></span>
         次
      </span>
    
    
      <span id="leancloud-site-uv-container" style="display: none">
        总访客数 
        <span id="leancloud-site-uv"></span>
         人
      </span>
    
    

  
</div>

  
  
    <!-- 备案信息 ICP for China -->
    <div class="beian">
  <span>
    <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
      蜀ICP备2023008943号
    </a>
  </span>
  
    
      <span>
        <a
          href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=https://beian.miit.gov.cn/"
          rel="nofollow noopener"
          class="beian-police"
          target="_blank"
        >
          
            <span style="visibility: hidden; width: 0">|</span>
            <img src="" srcset="/blog/img/loading.gif" lazyload data-original="/blog/img/police_beian.png" alt="police-icon"/>
          
          <span>京公网安备12345678号</span>
        </a>
      </span>
    
  
</div>

  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/blog/js/events.js" ></script>
<script  src="/blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script defer src="/blog/js/leancloud.js" ></script>

  <script  src="/blog/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>

        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var e=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,c=a();function a(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(){e&&(c=a());for(var t,o=0;o<c.length;o++)0<=(t=(t=c[o]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,n,a,i=c[o];e=function(){c=c.filter(function(t){return i!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(i)},(t=i).hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(n=new Image,a=t.getAttribute("data-original"),n.onload=function(){t.src=a,t.removeAttribute("data-original"),e&&e()},t.src!==a&&(n.src=a))}()}function i(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",i),r.addEventListener("resize",i),r.addEventListener("orientationchange",i)}(this);</script></body>
</html>
